<template>
  <div class="app-container">
    <!-- 页面标题和日期选择器 -->
    <div class="search-container">
      <el-form ref="queryFormRef" :inline="true" label-width="auto">
        <el-form-item label="选择日期">
          <el-date-picker
            v-model="selectedDate"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
            :disabled-date="disabledDate"
            @change="handleDateChange"
            clearable
          />
        </el-form-item>
        <el-form-item class="search-buttons">
          <div class="text-sm text-gray-500">
            数据更新时间：{{ formatDateTime(reportData?.updateTime) || '--' }}
          </div>
        </el-form-item>
        <el-form-item>
          <el-dropdown @command="handleExport" :disabled="!reportData || loading">
            <el-button type="primary" :loading="exportLoading">
              <el-icon><Download /></el-icon>
              导出报告
              <el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="pdf">
                  <el-icon><Document /></el-icon>
                  导出为PDF
                </el-dropdown-item>
                <el-dropdown-item command="png">
                  <el-icon><Picture /></el-icon>
                  导出为PNG图片
                </el-dropdown-item>
                <el-dropdown-item command="jpeg">
                  <el-icon><Picture /></el-icon>
                  导出为JPEG图片
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </el-form-item>
      </el-form>
    </div>

    <!-- 导出内容区域 -->
    <div ref="exportContentRef" class="export-content">
      <el-card shadow="hover" class="mb-4">
        <div class="daily-title">日报看板</div>
        <!-- 数据卡片展示 -->
        <div v-loading="loading" class="grid-container">
          <!-- 客单价 -->
          <div class="metric-card">
            <div class="metric-icon">
              <span class="icon">¥</span>
            </div>
            <div class="metric-content">
              <div class="metric-title">客单价</div>
              <div class="metric-value">{{ formatNumber(reportData?.averageTransactionValue) }}</div>
              <div class="metric-subtitle">本月平均: {{ formatNumber(reportData?.avgTransactionValue) }}</div>
            </div>
          </div>

          <!-- 转化率 -->
          <div class="metric-card">
            <div class="metric-icon">
              <span class="icon">%</span>
            </div>
            <div class="metric-content">
              <div class="metric-title">转化率</div>
              <div class="metric-value">{{ formatPercent(reportData?.conversionRate) }}%</div>
              <div class="metric-subtitle">本月平均: {{ formatPercent(reportData?.avgConversionRate) }}%</div>
            </div>
          </div>

          <!-- 销售进度 -->
          <div class="metric-card">
            <div class="metric-icon">
              <span class="icon">%</span>
            </div>
            <div class="metric-content">
              <div class="metric-title">销售进度</div>
              <div class="metric-value">{{ formatPercent(reportData?.salesProgress) }}%</div>
              <div class="metric-subtitle">时间进度: {{ formatPercent(reportData?.timeProgress) }}%</div>
            </div>
          </div>

          <!-- 销售数量 -->
          <div class="metric-card">
            <div class="metric-icon">
              <span class="icon">件</span>
            </div>
            <div class="metric-content">
              <div class="metric-title">本月销售数量</div>
              <div class="metric-value">{{ formatNumber(reportData?.totalSalesQuantity) }}</div>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 详细数据 -->
      <el-card shadow="hover">
        <template #header>
          <div class="card-header">
            <span>详细数据</span>
          </div>
        </template>
        
        <div class="data-container">
          <!-- 销售数据 -->
          <div class="data-section">
            <div class="section-title">销售数据</div>
            <el-table :data="[reportData || {}]" border style="width: 100%">
              <el-table-column prop="monthlySalesTarget" label="月度销售任务" align="center">
                <template #default="scope">
                  ¥{{ formatNumber(scope.row.monthlySalesTarget) }}
                </template>
              </el-table-column>
              <el-table-column prop="currentSalesAmount" label="已完成销售额" align="center">
                <template #default="scope">
                  ¥{{ formatNumber(scope.row.currentSalesAmount) }}
                </template>
              </el-table-column>
              <el-table-column prop="salesProgress" label="完成率" align="center">
                <template #default="scope">
                  {{ formatPercent(scope.row.salesProgress) }}%
                </template>
              </el-table-column>
              <el-table-column prop="timeProgress" label="时间进度" align="center">
                <template #default="scope">
                  {{ formatPercent(scope.row.timeProgress) }}%
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!-- 关键指标 -->
          <div class="data-section mt-4">
            <div class="section-title">关键指标</div>
            <el-table :data="[reportData || {}]" border style="width: 100%">
              <el-table-column prop="gmvYoyChange" label="GMV同比变化" align="center">
                <template #default="scope">
                  <span :class="getChangeClass(scope.row.gmvYoyChange)">
                    {{ formatPercent(scope.row.gmvYoyChange, true) }}%
                  </span>
                </template>
              </el-table-column>
              <el-table-column prop="averageTransactionValue" label="客单价" align="center">
                <template #default="scope">
                  ¥{{ formatNumber(scope.row.averageTransactionValue) }}
                </template>
              </el-table-column>
              <el-table-column prop="conversionRate" label="转化率" align="center">
                <template #default="scope">
                  {{ formatPercent(scope.row.conversionRate) }}%
                </template>
              </el-table-column>
              <el-table-column prop="avgTransactionValue" label="本月平均客单价" align="center">
                <template #default="scope">
                  ¥{{ formatNumber(scope.row.avgTransactionValue) }}
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!-- 进度条 -->
          <div class="data-section mt-4">
            <div class="section-title">销售进度</div>
            <div class="progress-item">
              <div class="progress-label">
                <span>销售进度</span>

              </div>
              <el-progress 
                :percentage="reportData?.salesProgress || 0" 
                :color="getProgressColor(reportData?.salesProgress)"
                :stroke-width="8"
              />
            </div>
            <div class="progress-item mt-3">
              <div class="progress-label">
                <span>时间进度</span>
              </div>
              <el-progress 
                :percentage="reportData?.timeProgress || 0" 
                color="#909399"
                :stroke-width="8"
              />
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 空状态 -->
    <el-empty v-if="!loading && !reportData" description="当前日期没有日报数据"></el-empty>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "DailyDashboard",
  inheritAttrs: false,
});

import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Download, ArrowDown, Document, Picture } from '@element-plus/icons-vue';
import DailySalesReportAPI, { DailySalesReportVO } from '@/api/system/daily-sales-report';
import { ExportUtils } from '@/utils/export';

// 响应式数据
const loading = ref(false);
const exportLoading = ref(false);
const selectedDate = ref<string>('');
const availableDates = ref<string[]>([]);
const reportData = ref<DailySalesReportVO | null>(null);
const exportContentRef = ref<HTMLElement>();

// 初始化数据
onMounted(async () => {
  await loadAvailableDates();
  
  // 如果有可用日期就加载第一个日期的数据，否则显示示例数据
  if (availableDates.value.length > 0) {
    selectedDate.value = availableDates.value[0];
    await loadReportData(selectedDate.value);
  } else {
    // 如果没有获取到日期，显示示例数据
    loadDemoData();
  }
});

// 加载示例数据
const loadDemoData = () => {
  const now = new Date();
  reportData.value = {
    reportDate: now.toISOString().split('T')[0],
    averageTransactionValue: 268.50,
    conversionRate: 0.0458,
    monthlySalesTarget: 1200000.00,
    currentSalesAmount: 456780.00,
    salesProgress: 38.07,
    timeProgress: 33.33,
    gmvYoyChange: 15.25,
    avgConversionRate: 0.0425,
    avgTransactionValue: 255.80,
    totalSalesQuantity: 1850,
    updateTime: now.toISOString() // 确保有格式化的时间
  };
};

// 加载可用日期列表
const loadAvailableDates = async () => {
  try {
    loading.value = true;
    // 调用API获取日期列表
    const dates = await DailySalesReportAPI.getAvailableDates();
    
    // 检查返回结果
    if (dates && Array.isArray(dates) && dates.length > 0) {
      availableDates.value = dates.sort((a, b) => b.localeCompare(a)); // 降序排列，最新的在前
      console.log('获取到可用日期列表:', availableDates.value);
    } else {
      console.warn('未获取到可用日期列表或列表为空');
      availableDates.value = [];
    }
  } catch (error) {
    console.error('加载日期列表失败:', error);
    ElMessage.error('加载日期列表失败，将显示示例数据');
    availableDates.value = [];
  } finally {
    loading.value = false;
  }
};

// 加载报告数据
const loadReportData = async (date: string) => {
  if (!date) {
    loadDemoData();
    return;
  }
  
  try {
    loading.value = true;
    const data = await DailySalesReportAPI.getReportByDate(date);
    
    if (data) {
      reportData.value = data;
      console.log('获取到日报数据:', data);
      // 添加更多日志记录来检查数据格式
      console.log('更新时间:', data.updateTime, '类型:', typeof data.updateTime);
      console.log('完整数据结构:', JSON.stringify(data, null, 2));
    } else {
      console.warn(`未获取到日期 ${date} 的日报数据，将显示示例数据`);
      loadDemoData();
    }
  } catch (error) {
    console.error('加载报告数据失败:', error);
    ElMessage.error('加载报告数据失败，将显示示例数据');
    loadDemoData();
  } finally {
    loading.value = false;
  }
};

// 日期变化处理
const handleDateChange = (date: string) => {
  if (date) {
    ElMessage.info('正在加载数据，请稍候...');
    loadReportData(date);
  } else {
    reportData.value = null;
  }
};

// 禁用不可选日期
const disabledDate = (time: Date) => {
  // 如果没有可用日期列表，则禁用所有日期
  if (!availableDates.value || availableDates.value.length === 0) {
    return true;
  }
  
  // 将Date对象转换为YYYY-MM-DD格式的字符串
  try {
    const dateStr = time.toISOString().split('T')[0];
    return !availableDates.value.includes(dateStr);
  } catch (error) {
    console.error('日期转换错误:', error);
    return true; // 出错时禁用该日期
  }
};

// 格式化数字
const formatNumber = (value?: number) => {
  if (value === undefined || value === null) return '--';
  return value.toLocaleString();
};

// 格式化百分比
const formatPercent = (value?: number, showSign = false) => {
  if (value === undefined || value === null) return '--';
  const formatted = value.toFixed(2);
  if (showSign && value > 0) {
    return `+${formatted}`;
  }
  return formatted;
};

// 获取变化值的样式类
const getChangeClass = (value?: number) => {
  if (value === undefined || value === null) return '';
  if (value > 0) return 'text-success';
  if (value < 0) return 'text-danger';
  return '';
};

// 获取进度条颜色
const getProgressColor = (value?: number) => {
  if (!value) return '#909399';
  if (value >= 80) return '#67c23a';
  if (value >= 60) return '#e6a23c';
  return '#f56c6c';
};

// 格式化日期时间
const formatDateTime = (dateTimeStr?: string) => {
  if (!dateTimeStr) return '--';
  
  try {
    const date = new Date(dateTimeStr);
    if (isNaN(date.getTime())) return '--';
    
    return `${date.getFullYear()}/${(date.getMonth() + 1).toString().padStart(2, '0')}/${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;
  } catch (error) {
    console.error('日期格式化错误:', error);
    return '--';
  }
};

// 导出报告
const handleExport = async (command: string) => {
  if (!reportData.value || !exportContentRef.value) return;

  try {
    exportLoading.value = true;
    
    // 生成文件名
    const dateStr = selectedDate.value || ExportUtils.getDateTimeString().slice(0, 8);
    const timeStr = ExportUtils.getDateTimeString().slice(9);
    const filename = ExportUtils.sanitizeFilename(`销售日报_${dateStr}_${timeStr}`);

    // 根据命令类型导出
    if (command === 'pdf') {
      await ExportUtils.exportToPDF(exportContentRef.value, filename, {
        orientation: 'portrait',
        format: 'a4',
        margin: { top: 15, right: 15, bottom: 15, left: 15 }
      });
    } else if (command === 'png') {
      await ExportUtils.exportToImage(exportContentRef.value, filename, {
        format: 'png',
        scale: 2,
        backgroundColor: '#ffffff'
      });
    } else if (command === 'jpeg') {
      await ExportUtils.exportToImage(exportContentRef.value, filename, {
        format: 'jpeg',
        quality: 0.95,
        scale: 2,
        backgroundColor: '#ffffff'
      });
    }
  } catch (error) {
    console.error('导出报告失败:', error);
    ElMessage.error('导出报告失败，请重试');
  } finally {
    exportLoading.value = false;
  }
};
</script>

<style scoped>
.search-container {
  margin-bottom: 16px;
}

.daily-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #303133;
}

.grid-container {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-gap: 20px;
}

.metric-card {
  display: flex;
  align-items: center;
  padding: 12px;
  border-radius: 4px;
  background-color: #f5f7fa;
}

.metric-icon {
  width: 48px;
  height: 48px;
  border-radius: 4px;
  background-color: #409eff;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
}

.icon {
  font-size: 18px;
  font-weight: bold;
}

.metric-content {
  flex: 1;
}

.metric-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 4px;
}

.metric-value {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
}

.metric-subtitle {
  font-size: 12px;
  color: #909399;
  margin-top: 2px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 12px;
  color: #303133;
}

.progress-item {
  margin-bottom: 8px;
}

.progress-label {
  display: flex;
  justify-content: space-between;
  margin-bottom: 6px;
  font-size: 14px;
  color: #606266;
}

.data-section {
  margin-bottom: 20px;
}

.card-header {
  font-size: 16px;
  font-weight: bold;
}

.text-success {
  color: #67c23a;
}

.text-danger {
  color: #f56c6c;
}

.export-content {
  background: #ffffff;
  padding: 20px;
  border-radius: 8px;
}

/* 导出时隐藏不必要的元素 */
@media print {
  .search-container {
    display: none !important;
  }
  
  .export-content {
    padding: 0;
    box-shadow: none;
    border-radius: 0;
  }
  
  .el-card {
    box-shadow: none !important;
    border: 1px solid #ddd !important;
  }
}

/* 确保导出时的字体和颜色正确显示 */
.export-content * {
  -webkit-print-color-adjust: exact !important;
  color-adjust: exact !important;
  print-color-adjust: exact !important;
}

@media (max-width: 1200px) {
  .grid-container {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .grid-container {
    grid-template-columns: 1fr;
  }
}
</style> 
